import { Cloud } from '@tbmp/mp-cloud-sdk';
import { Emitter } from 'tb-shop-sdk';
import Mfutil from './utils/mfutil/index';
import config from './config';
const cloud = new Cloud();

let env = {
  dev: { api: 'vans-family', env: 'test' },
  qa: { api: 'vans-family-qa', env: 'test' },
  online: { api: 'vans-family', env: 'online' },
}
env = env.dev

// 云应用初始化
cloud.init({
  env: env.env,
});
const emitter = new Emitter();
const mfutil = new Mfutil({ config });
mfutil.init({ cloud, emitter });
let _that = null;
App({
  globalData: {
    userInfo: {
      name: '',
      integral: '',
      availablePoint: '',   //总积分
      birthDate: '',
      mobilePhone: '',
      province: '',
      city: '',
      interests: '',
      shoeSize: '',
      brandTenure: '',
      email: '',
      genderCode: '',
      memberId: '',
    },
    // user_nick: 'zddi26',
    user_nick: '',
    accessToken: null,
    Location: null,
    screenHeight: 0,
    params: [],
    loadingActive: false
  },

  // 当应用初始化完成时触发，全局只触发一次
  async onLaunch(options) {
    let { query } = options;
    // my.previewImage({
    //       current: 2,
    //       urls: [
    //         'https://morefun-active.oss-cn-beijing.aliyuncs.com/c2b/1.gif',
    //         'https://img.alicdn.com/tps/TB1pfG4IFXXXXc6XXXXXXXXXXXX.jpg',
    //         'https://img.alicdn.com/tps/TB1h9xxIFXXXXbKXXXXXXXXXXXX.jpg'
    //       ],
    //     });

    try {
      _that = this;
      _that.globalData.params = query && query.params.split(',').slice(0, 2);
      _that.globalData.channel = query ? query.params.split(',')[2] : ''

    } catch (e) {

      my.alert({
        title: 'eeeeee',
        content: JSON.stringify(e),
        buttonText: '',
        success: () => {

        },
        fail: () => {

        },
        complete: () => {

        }
      });
    }

    // this.addUserStat({type:true,channel:_that.globalData.channel })

    // this.addUserStat({customType:`点击了tile-1-testan`})
  },
  // 从后台被 scheme 重新打开
  onShow(options) {
    mfutil.onShow(options);
  },
  // 当应用从前台进入后台时触发
  onHide() {
    mfutil.onHide();
  },
  cloud,
  emitter,
  mfutil,
  async UserAccess(options) {
    let time = new Date().getTime();
    let trackObj = {
      "project": "vanscn",
      "event_key": "$useraction",
      "event_type": "track",
      "event_time": time,
      "event_id": _that.globalData.user_nick + '' + time,
      "detail_id": _that.globalData.user_nick + '' + _that.globalData.accessToken,
      "card_number_code": _that.globalData.userInfo.memberId,
      "customer_id": _that.globalData.user_nick,
      "channel": "100000020",
      "grade": options.grade || '',
      "code": "0.0.0.0",
      "string1": "",
      "string2": "",
      "string3": options.String3 || '',
      "name": options.name || '',
      "address": options.address || '',
      "string4": options.String4 || '',
      "string5": _that.globalData.SystemInfo.brand,
      "string6": _that.globalData.SystemInfo.model,
      "string7": _that.globalData.SystemInfo.platform,
      "string8": _that.globalData.SystemInfo.language
    }
    let path = '/vans-family/api/v2.1/project/vansFamily/track/add';
    try {
      let res = await cloud.application.httpRequest({
        path,
        method: 'POST',
        'headers': {
          "content-type": "application/json",
        },
        params: '',
        body: trackObj,
        //对于一个小程序关联多个云应用的场景，调用非默认云应用，需要指定对应的云应用Id,超时时间单位ms
        'exts': { "timeout": 10000 }
      });

      if (res.success) {
        console.warn(`${options.address}埋点结果成功-----${JSON.stringify(res)}`)

      } else {
        console.error(`${options.address}埋点结果失败-----${JSON.stringify(res)}`)
      }
    } catch (e) {
      console.warn('埋点异常', e);
    }
  },
  //page调用接口的方法
  async HTTPOuid(path, method, params = '', body = {}) {

    let result = ''
    try {
      result = await cloud.application.httpRequest({
        path,
        method,
        'headers': {
          "content-type": "application/json",
        },
        params,
        body,
        //对于一个小程序关联多个云应用的场景，调用非默认云应用，需要指定对应的云应用Id,超时时间单位ms
        'exts': { "cloudAppId": "34156", "timeout": 10000 }
      });
      console.log(`${path}请求成功`, result);
      getApp().globalData.loadingActive = false;
      return result;
    } catch (e) {
      getApp().globalData.loadingActive = false;
      mfutil.launchErrPage(53001)
    }
  },

  // 埋点
  async addUserStat(data) {
    // debugger
    console.log(_that.globalData.channel + 'asdhajshdjahdjashdasgdasgdhas')
    const { type = null, customType = null, } = data

    try {

      let info = {
        version: "v2",
        projectCode: '2091',
        timestamp: new Date().getTime().toString(),
        province: "",
        city: "",
        platform: "Taobao",
        channel: _that.globalData.channel,
        userId: _that.globalData.user_nick,
        tileId: data.tileId || '',
        points: data.points || '',
        ctabtn: data.ctabtn || ''
        // value:
      }
      if (type) {
        info.type = 'flowSource'
      }
      if (customType) {
        info.customType = customType;
      }
      let path = '/vans-family/api/v2_1/tracking/rocket/tcp/producer'
      // go-tracking-mq-gateway/api/v2.1/tracking/rocket/tcp/producer
      let res = await cloud.application.httpRequest({
        path,
        method: 'post',
        'headers': {
          "content-type": "application/json",
        },
        params: '',
        body: info,
        dataType: "json",
        //对于一个小程序关联多个云应用的场景，调用非默认云应用，需要指定对应的云应用Id,超时时间单位ms
        'exts': { "timeout": 10000 }
      });
      console.log(res + '自定义埋点成功了');

      res = this.HttpRequest('/vans-family/api/v2_1/tracking/rocket/tcp/producer?msg=' + JSON.stringify(info), 'GET',);
      console.log(6666666666666666666 + res);


      if (res.success) {

        console.warn(`${options.address}自定义埋点结果成功-----${JSON.stringify(res)}`)
      } else {
        console.error(`${options.address}自定义埋点结果失败-----${JSON.stringify(res)}`)
      }
    } catch (e) {
      // debugger
      return { isOk: 0, msg: '铺捉到错误' + e };
    }
  },
  //page调用接口的方法
  async HttpRequest(path, method, params = '', body = {}) {

    try {

      let newpath = path.substring(12)
      console.log(env.api + newpath);
      let result = await cloud.application.httpRequest({
        path: env.api + newpath,
        method,
        'headers': {
          "content-type": "application/json",
        },
        params,
        body,
        //对于一个小程序关联多个云应用的场景，调用非默认云应用，需要指定对应的云应用Id,超时时间单位ms
        'exts': { "timeout": 10000 }
      });
      console.log(`${path}请求成功`, result);
      getApp().globalData.loadingActive = false;
      return result;
    } catch (e) {
      getApp().globalData.loadingActive = false;
      console.log(e, "##############################EE");
      mfutil.launchErrPage(53001)
    }
  },
  async CloudFunction(handler, data = {}) {
    let res = await cloud.function.invoke('agreement', data, handler);
    return res
  },
  URLChangeCommon2(options) {
    if (options.cta_button_link.includes('http')) {
      my.call("navigateToOutside", {
        url: options.cta_button_link
      })
    } else {
      my.reLaunch({
        url: options.cta_button_link
      })
    }
  },


  URLChangeCommon(options) {

    if (options.option === 1 || !options.option) {
      my.reLaunch({
        url: options.cta_button_link
      })
    }
    if (options.option === 2) {
      my.call("navigateToOutside", {
        url: options.cta_button_link
      })
    }
    if (options.option === 3) {
      my.call("navigateToOutside", {
        url: options.cta_button_link
      })
    }
  },


  //分享
  onShareAppMessage() {
    return {
      title: 'VANS',
      imageUrl: 'https://morefun-active.oss-cn-beijing.aliyuncs.com/vans-family/1.png',
      desc: 'Vans会员之家',
      path: 'pages/index/index',
      // url: 'https://m.duanqu.com?_ariver_appid=3000000002032702&page=page%2fcomponent%2fcomponent-pages%2fview%2fview%3fparam%3d123'
    };
  }
});